package com.marcjmcd.cop4331;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TextToSpeech extends Activity
{
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tts);
		
		
		Button say = (Button) findViewById(R.id.button10);
		
		say.setOnClickListener(new OnClickListener() {
			
		@Override
		public void onClick(View v) 
		{
			tts();			
		}
		});
		
		
		Button back = (Button) findViewById(R.id.button9);
		
		back.setOnClickListener(new OnClickListener() {
			
		@Override
		public void onClick(View v) 
		{
			Context context = getApplicationContext();
			
			startActivity(new Intent(context, Main.class));
		}
		});
	}
	
	private void tts()
	{
		EditText input = (EditText) findViewById(R.id.tts_input);
		String text = "";
		
		text = input.getText().toString();
		
		if(text.equals(""))
		{
			Context context = getApplicationContext();
	        int duration = Toast.LENGTH_SHORT;
	    	
			Toast toast = Toast.makeText(context, "Please Enter Some Text", duration);
			toast.setGravity(Gravity.BOTTOM, 0, 75);

	        toast.show();
		}
		else
		{

			MediaPlayer mp = new MediaPlayer(); 
			
			try
			{
				//Tells the media player where the source for the .mp3 is.  Also, replaces spaces with %20 (URL syntax)
				mp.setDataSource("http://translate.google.com/translate_tts?" + "q=" + text.replace(" ", "%20")
	             + "&tl=en" + ".mp3");
				mp.prepare();
				
				mp.start();
			}
			catch(Exception e)
			{
				//Catches network exceptions
				System.out.println("Exception: " + e);
			}
		}
	}
}
